<template>
  <div>
    <div class="select-platform">
      <el-radio-group class="platform-radio" v-model="formType" size="small">
        <el-radio-button :label="1">单个上传</el-radio-button>
        <el-radio-button :label="2">批量上传</el-radio-button>
      </el-radio-group>
      <div style="margin-top: 15px; ">
        <hr style="border: 1px solid rgba(200, 200, 200, 0.3);">
        <br>
      </div>
    </div>
    <template v-if="formType === 1">
      <el-form
        ref="packetGoodsForm"
        :model="form"
        label-width="150px"
        :rules="rules"
        class="form"
      >
        <div class="block">
          <div class="title">{{ $t('packet.基础信息') }}</div>
          <div class="items">
            <el-form-item :label="$t('packet.商品标题')" prop="title">
              <el-input v-model="form.title" :placeholder="$t('packet.请输入')"></el-input>
            </el-form-item>
            <el-form-item :label="$t('packet.商品SKU')" prop="sku">
              <el-input v-model="form.sku" :placeholder="$t('packet.请输入')"></el-input>
            </el-form-item>
            <el-form-item :label="$t('packet.商品图片')" prop="image">
              <el-button type="primary" @click="uploadImage">{{ $t('packet.上传图片') }}</el-button>
              <img :src="form.image" alt="" class="image">
            </el-form-item>
          </div>
        </div>
        <div class="block" >
          <div class="title">{{ $t('packet.商品属性') }}</div>
          <div class="items">
            <el-form-item :label="$t('packet.重量（kg）')" prop="weight" >
              <el-input-number v-model="form.weight" class="size-input" :min="0" :max="999" :precision="2" :controls="false" :disabled="disabled"></el-input-number>
              <div class="tips">{{ $t('packet.请填写单个商品打包好的尺寸和重量（整个包裹）') }}</div>
            </el-form-item>
            <el-form-item :label="$t('packet.尺寸（cm）')" required>
              <div class="size-input-box">
                <el-form-item prop="length">
                  <span class="mgr10">{{ $t('packet.长') }}</span>
                  <el-input-number v-model="form.length" class="size-input" :min="0" :max="999" :precision="0" :controls="false" :disabled="disabled"></el-input-number>
                </el-form-item>
                <el-form-item prop="width">
                  <span class="mgr10">{{ $t('packet.宽') }}</span>
                  <el-input-number v-model="form.width" class="size-input" :min="0" :max="999" :precision="0" :controls="false" :disabled="disabled"></el-input-number>
                </el-form-item>
                <el-form-item prop="height">
                  <span class="mgr10">{{ $t('packet.高') }}</span>
                  <el-input-number v-model="form.height" class="size-input" :min="0" :max="999" :precision="0" :controls="false" :disabled="disabled"></el-input-number>
                </el-form-item>
              </div>
            </el-form-item>

            <el-form-item :label="$t('packet.箱装数')" prop="goodsNumInBox">
              <div class="goodsNumInBox">
                <el-input-number v-model="form.goodsNumInBox" class="size-input" :min="0" :precision="0" :controls="false"></el-input-number>
                <div class="mgl10">{{ $t('packet.个') }}/{{ $t('packet.箱') }}</div>
              </div>
            </el-form-item>
            <el-form-item
              :label="$t('table.整箱重量')"
              prop="packet_weight"

            >
              <el-input-number
                v-model="form.packet_weight"
                :controls="false"
                :min="0"
                :max="max"
                :precision="3"
                class="weight-input"
              >
              </el-input-number>
            <div class="tips" >按箱装数装满当前商品的箱子重量和尺寸（整箱）</div>

            </el-form-item>
            <el-form-item
              :label="$t('table.整箱尺寸')"
              required
            >
              <div class="size-input-box">
                <el-form-item prop="length">
                 <span class="mgr10">{{ $t('packet.长') }}</span>
                  <el-input-number
                    v-model="form.packet_length"
                    class="size-input"
                    :min="0"
                    :max="max"
                    :precision="0"
                    :controls="false"
                  >
                  </el-input-number>

                </el-form-item>

                <el-form-item prop="packet_width">
                  <span class="mgr10">{{ $t('packet.宽') }}</span>
                  <el-input-number
                    v-model="form.packet_width"
                    class="size-input"
                    :min="0"
                    :max="max"
                    :precision="0"
                    :controls="false"
                  >
                  </el-input-number>

                </el-form-item>

                <el-form-item prop="packet_height">
                  <span class="mgr10">{{ $t('packet.高') }}</span>
                  <el-input-number
                    v-model="form.packet_height"
                    class="size-input"
                    :min="0"
                    :max="max"
                    :precision="0"
                    :controls="false"
                  >
                  </el-input-number>

                </el-form-item>

              </div>

            </el-form-item>
          </div>
        </div>
        <div class="block">
          <div class="title">{{ $t('packet.报关信息') }}</div>

          <div class="items">
            <div class="tips" style="margin-left: 150px;margin-bottom: 15px;color: red;"> 头程发货需报关的商品，请完善以下报关信息</div>
            <el-form-item label="中文品名">
              <el-input v-model="form.goodsNameZh" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="Goods Name">
              <el-input v-model="form.goodsName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label="$t('packet.货值')" prop="goodsValue">
              <div class="goodsValue">
                <el-input type="number" v-model="form.goodsValue"  :min="0" :precision="0" :controls="false">
                    <template slot="append">USD/pc</template>
                </el-input>
                <!-- <div class="mgl10">USD/pc</div> -->
              </div>
            </el-form-item>
            <el-form-item label="材质（中英文）">
              <el-input v-model="form.material" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="用途（中英文）">
              <el-input v-model="form.application" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="品牌">
              <el-input v-model="form.brand" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="产品类型">
              <el-radio-group v-model="form.goodsType">
                <el-radio
                  v-for="item in allGoodsType"
                  :key="item"
                  :label="item"
                >
                  {{item}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="产品属性">
              <el-checkbox-group v-model="form.goodsAttr">
                <el-checkbox
                  v-for="item in allGoodsAttr"
                  :key="item"
                  :label="item"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
        </div>
        <div class="block">
          <div class="title">{{ $t('packet.其他信息') }}</div>
          <div class="items">

            <el-form-item :label="$t('packet.包装服务')" prop="packageMaterialId" prefix="packageMaterialId">
              <el-select v-model="form.packageMaterialId" :placeholder="$t('packet.请选择')">
                <el-option :label="$t('table.No packaging service')" :value='0'></el-option>
                <el-option
                  v-for="(item, index) in packageMaterial"
                  :key="index"
                  :label="item.name + '(' + item.price + $t('table.unit1') + ')'"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('packet.是否需组装')" prop="isCombination">
              <div class="isCombination" style="margin-top: 6px;">
                <el-switch v-model="form.isCombination">
                </el-switch>
              </div>
            </el-form-item>
          </div>
        </div>
        <div class="buttons">
          <el-button @click="$emit('back')">{{ $t('packet.返回') }}</el-button>
          <el-button type="primary" @click="submit">{{ $t('packet.确定') }}</el-button>
        </div>
      </el-form>
    </template>
    <template v-if="formType === 2">
      <div>
        <el-button size="small" type="primary" @click="getBatchUploadPacketGoodsTemplate">下载模板</el-button>
        <el-button size="small" type="success" @click="showDrawer">上传记录</el-button>
        <div style="margin-top: 10px; font-size: 14px;">
          请先下载模板，按模板填写商品信息后上传
        </div>
        <div style="margin-top: 10px;">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeader"
            :show-file-list="false"
            :on-success="uploadFileSuccess"
            :before-upload="beforeUpload"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将填写好的模板文件拖到此处或<em>点击上传</em></div>
          </el-upload>
        </div>
      </div>
      <el-drawer
        title="上传列表"
        :visible.sync="drawer"
        direction="rtl"
        size="1000px"
      >
        <el-table :data="drawerData">
          <el-table-column
            prop="id"
            label="ID"
            min-width="100"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="fileName"
            :label="$t('stock.file')"
            min-width="200"
            align="center"
          >
            <template slot-scope="{row}">
              <div class="font-blue" style="cursor: pointer" @click="downloadFile(row)">
                {{row.fileName || '-'}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="statusInfo"
            :label="'状态'"
            min-width="150"
            align="center"
          >
            <template slot-scope="{row}">
              <template v-if="row.status === 'fail'">
                <span class="font-red">{{row.statusStr}} <i class="el-icon-error"></i></span>
              </template>
              <template v-if="row.status === 'waiting'">
                <span class="font-blue">{{row.statusStr}} <i class="el-icon-loading"></i></span>
              </template>
              <template v-if="row.status === 'handling'">
                <span class="font-blue">{{row.statusStr}} <i class="el-icon-loading"></i></span>
              </template>
              <template v-if="row.status === 'success'">
                <span class="font-green">{{row.statusStr}} <i class="el-icon-success"></i></span>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="numInfo"
            :label="'处理结果'"
            min-width="150"
            align="center"
          >
            <template slot-scope="{row}">
              <template v-if="row.status === 'fail'">
                <span>—</span>
              </template>
              <template v-if="row.status === 'waiting'">
                <span>—</span>
              </template>
              <template v-if="row.status === 'handling'">
                <span>{{row.successNum}}/{{row.allNum}}</span>
              </template>
              <template v-if="row.status === 'success'">
                <span>
                  <span class="font-red" v-if="row.successNum !== row.allNum">{{row.successNum}}</span><span v-else>{{row.successNum}}</span>/{{row.allNum}}
                </span>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="isFailShow"
            :label="'失败原因'"
            min-width="100"
            align="center"
          >
            <template slot-scope="{row}">
              <template v-if="row.isFailShow === true">
                <el-button type="text" style="color: red;" @click="showFailData(row)">查看</el-button>
              </template>
              <template v-else>
                <span>—</span>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </template>
  </div>
</template>

<script>
import {getUserPackageMaterialSetting, getBatchUploadPacketGoodsList, getBatchUploadPacketGoodsTemplate} from "@/api/packetGoods";
import {startUpload} from "@/utils";
import {uploadImage} from "@/api/common";
import {getToken} from "@/utils/auth";
import {getGoodsOptions} from "@/api/goods";
export default {
  props: {
    form: {
      type: Object,
      default() {
        return {
          title: '',
          sku: '',
          image: '',
          length: 0,
          width: 0,
          height: 0,
          weight: 0,
          goodsNumInBox: 0,
          packageMaterialId: 0,
          goodsValue: 0,
          isCombination: 0,
          goodsNameZh: '',
          goodsName: '',
          material: '', // 材质
          application: '', // 用途
          brand: '', // 品牌
          packet_weight: 0,
          packet_length: 0,
          packet_width: 0,
          packet_height: 0,
          goodsType: '',
          goodsAttr: [],
        };
      },
    },
    type: {
      type: String
    },
  },
  data() {

    const rules = {
      title: [
        {required: false, message: this.$t('packet.请输入商品标题'), trigger: 'blur'},
      ],
      sku: [
        {required: false, message: this.$t('packet.请输入商品SKU'), trigger: 'blur'},
      ],
      weight: [
        {type:'number', required: true, message: this.$t('stock.重量请填写大于0的数字'), trigger: 'blur',min:0.1},
      ],
      length: [
        {type:'number', required: true, message: this.$t('stock.长请填写大于0的数字'), trigger: 'blur',min:1}
      ],
      width: [
        {type:'number', required: true, message: this.$t('stock.宽请填写大于0的数字'), trigger: 'blur',min:1},
      ],
      height: [
        {type:'number', required: true, message: this.$t('stock.高请填写大于0的数字'), trigger: 'blur',min:1},
      ],
      // goodsValue: [
      //   {type:'number', required: false, message: this.$t('packet.请输入货值'), trigger: 'blur', min:1},
      // ],
      goodsNumInBox: [
        {type:'number', required: true, message: this.$t('packet.请输入箱装数'), trigger: 'blur', min:1},
      ],
      packageMaterialId: [
        {required: true, message: this.$t('packet.请选择包装服务'), trigger: 'blur'},
      ],
      image: [
        {required: true, message: this.$t('packet.请上传商品图片')},
      ],
      packet_weight: [
        {type:'number', required: true, message: this.$t('stock.重量请填写大于0的数字'), trigger: 'blur',min:0.1},
      ],
      packet_length: [
        {type:'number', required: true, message: this.$t('stock.长请填写大于0的数字'), trigger: 'blur',min:1}
      ],
      packet_width: [
        {type:'number', required: true, message: this.$t('stock.宽请填写大于0的数字'), trigger: 'blur',min:1},
      ],
      packet_height: [
        {type:'number', required: true, message: this.$t('stock.高请填写大于0的数字'), trigger: 'blur',min:1},
      ],
    }

    return {
      packageMaterial: [],
      rules,
      formType: 1,
      uploadUrl: process.env.VUE_APP_BASE_API + '/packetGoods/batchUploadPacketGoodsInfo',
      uploadHeader: {
        Authorization: 'Bearer ' + getToken(),
      },
      drawer: false,
      drawerData: [],
      drawerParams: {
        page: 1,
        drawerType: 'goods',
      },
      interval: null,
      exportTemplate: '',
      max: 999999,
      allGoodsType:[],
      allGoodsAttr:[],
    }
  },

  computed: {
    disabled(){
      if(this.type=='update'){
        return true
      }
      return false
    },
    isInterval(){
      return this.drawerData.some(item=>{
        if(item.status === 'waiting' || item.status === 'handling'){
          return true
        }
        return false
      })
    },
  },
  created() {
    this.getOptions()
    this.getUserPackageMaterialSetting();
    this.interval = setInterval(()=>{
      // 请求数量 但没有loading效果
      if(this.isInterval && this.drawer){
        this.getDrawerData()
      }
    },1500)

  },
  methods: {
     getOptions(){
       getGoodsOptions()
        .then(res=>{
            // DOM更新后的操作
            this.allGoodsType = res.data.goodsType
            this.allGoodsAttr = res.data.goodsAttr

        })

    },
    getUserPackageMaterialSetting() {
      getUserPackageMaterialSetting()
          .then(res => {
            this.packageMaterial = res.data;
          })

    },

    submit() {
      this.$refs.packetGoodsForm.validate((valid) => {
        if (valid) {
          this.$emit('submit', this.form);
        }
      });
    },

    uploadImage() {
      startUpload({
        accept: '.jpg,.jpeg,.png',
      })
          .then(event => {
            const file = event?.target?.files[0];
            if (!file) {
              return;
            }

            // 检查文件大小不能超过1m
            if (file.size > 1024 * 1024) {
              this.$message.error(this.$t('图片大小不能超过1M'));
              return;
            }

            const formData = new FormData();
            formData.append('file', file);
            uploadImage(formData)
                .then(res => {
                  this.form.image = res.info.imageUrl;
                });
          });

    },

    getBatchUploadPacketGoodsTemplate(){
      getBatchUploadPacketGoodsTemplate()
        .then(response =>{
          // 创建 Blob 对象
          const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

          // 创建文件对象 URL
          const excelFile = window.URL.createObjectURL(blob);

          // 创建下载链接
          const link = document.createElement('a');
          link.href = excelFile;
          link.download = '批量上传小包商品.xlsx';  // 文件名可自定义
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);

          // 释放URL对象
          setTimeout(() => {
            URL.revokeObjectURL(excelFile);
          }, 60000); // 60秒后释放
        })
    },

    uploadFileSuccess(res, file) {
      if (res.error === 0) {
        this.$successMessage(res.message)
        this.showDrawer()
      } else {
        this.$errorMessage(res.message);
      }
    },

    beforeUpload(){
      return true
    },

    showDrawer() {
      this.drawer = true
      this.drawerParams.page = 1;
      this.getDrawerData()
    },

    getDrawerData() {
      getBatchUploadPacketGoodsList()
        .then(res => {
          this.drawerData = res.data;
        })
    },

    downloadFile(row) {
      if(!row.filePath){
        return
      }
      window.open(row.filePath,"_blank");
    },

    showFailData(row) {
      //跳转页面查看错误数据
      let routeUrl = this.$router.resolve({
        name: 'batchUploadPacketErrorData',
        query: {
          'id' : row.id,
          'type': 'goods',
        }
      })
      // 新标签打开路由
      window.open(routeUrl.href, '_blank');
    },
  },
  beforeDestroy() {
    if (this.interval) {
      clearInterval(this.interval)
    }
  },
}
</script>

<style>
.platform-radio{
.el-radio-button__inner{

}
.el-radio-button__inner:hover {
  color: #ff6d6d;
}
.el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: #FFFFFF;
  background-color: #ff6d6d;
  border-color: #ff6d6d;
  -webkit-box-shadow: -1px 0 0 0 #ff6d6d;
  box-shadow: -1px 0 0 0 #ff6d6d;
}
}
</style>

<style scoped lang="less">
.form{
  padding: 20px;
  @imageWidth: 100px;
  .image{
    display: block;
    width: @imageWidth;
    min-height: @imageWidth;
    margin-top: 16px;
    background: lightgray;
  }
  .tips{
    color: #999;
    font-size: 12px;
    margin-top: 5px;
  }
  .goodsNumInBox{
    display: flex;
  }
  .goodsValue{
    display: flex;
  }
  .isCombination{
    display: flex;
  }
  .size-input{
     width: 120px;
    ::v-deep .el-input-group__append{
      padding: 0 15px !important;
    }
  }
  .size-input-box{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
}
.block{
  width: 600px;
  .title{
    font-size: 16px;
    font-weight: bold;
    padding: 0 0 12px;
  }
}
.buttons{
  margin-top: 30px;
}
</style>
